package org.flint.data.structure.leetcode;

/**
 * @author flint92
 */
public class NumArray2 {

    /**
     * sum中 sum[i]存储的是nums[0...i-1]所有元素的和 sum[0] = 0
     */
    private int[] sum;

    public NumArray2(int[] nums) {
        int len;
        if (nums == null || (len = nums.length) == 0) {
            throw new IllegalArgumentException("nums must not be empty.");
        }
        sum = new int[len + 1];
        sum[0] = 0;
        for (int i = 1; i < sum.length; i++) {
            sum[i] = sum[i - 1] + nums[i - 1];
        }
    }

    /**
     * NumArray问题中的第二种解法
     */
    public int sumRange(int i, int j) {
        if (i > j) {
            throw new IllegalArgumentException("i must less equal than j");
        }
        return sum[j + 1] - sum[i];
    }

    public static void main(String[] args) {
        int[] nums = new int[]{-2, 0, 3, -5, 2, -1};
        NumArray2 numArray = new NumArray2(nums);
        assert 1 == numArray.sumRange(0, 2);
        assert -1 == numArray.sumRange(0, 5);
        assert -3 == numArray.sumRange(2, 5);
    }

}
